//
//  DFProductsRightTableViewController.m
//  cf
//
//  Created by lanou on 15/10/24.
//  Copyright © 2015年 xuzenghui. All rights reserved.
//

#import "DFProductsRightTableViewController.h"
#import "DFProductsRightTableViewCell.h"
#import "PKRequestManager.h"
#import "DFProductSortListModel.h"
#import "UIImageView+WebCache.h"
#import "DFProductsDetailViewController.h"
#import "FMDatabase.h"
@interface DFProductsRightTableViewController ()

@property (nonatomic,strong)NSMutableArray *secondMenuArr;
@property (nonatomic,strong)NSMutableArray *thirdMenuArr;
@property (nonatomic,strong)NSMutableArray *secondValueArr;
@property (nonatomic,strong)NSArray *valueArr;
@property (nonatomic , assign)NSInteger selectedIndex;
@property (nonatomic,strong)FMDatabase *dataBase;
@property (nonatomic,strong)NSMutableArray *NorequestArr;
@property (nonatomic,strong)NSMutableArray *NorequestVArr;
@end

@implementation DFProductsRightTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _NorequestArr = [NSMutableArray array];
    NSArray *com = @[@"台式电脑",@"一体机"];
    NSArray *wear = @[@"智能手环",@"智能手表",@"智能眼镜"];
    NSArray *photo = @[@"数码相机",@"镜头",@"数码摄像机",@"拍立得"];
    
    NSArray *setCom = @[@"显卡",@"CPU",@"主板",@"机箱",@"固态硬盘",@"内存",@"硬盘",@"电源",@"DIY组装",@"散热器",@"声卡",@"光驱"];
    NSArray *digtal = @[@"U盘",@"移动硬盘",@"麦克风",@"摄像头"];
    NSArray *setComOut = @[@"液晶显示器",@"音箱",@"鼠标",@"键盘",@"键鼠套装"];
    [_NorequestArr addObject:com];
    [_NorequestArr addObject:wear];
    [_NorequestArr addObject:photo];
    [_NorequestArr addObject:setCom];
    [_NorequestArr addObject:digtal];
    [_NorequestArr addObject:setComOut];
    
    _NorequestVArr = [NSMutableArray array];
    NSArray *comV = @[@"27",@"641"];
    NSArray *wearV = @[@"827",@"829",@"832"];
    NSArray *photoV = @[@"15",@"268",@"81",@"847"];
    
    NSArray *setComV = @[@"6",@"28",@"5",@"10",@"626",@"3",@"2",@"35",@"841",@"67",@"7",@"96"];
    NSArray *digtalV = @[@"37",@"274",@"669",@"60"];
    NSArray *setComOutV = @[@"84",@"34",@"32",@"33",@"100"];
    [_NorequestVArr addObject:comV];
    [_NorequestVArr addObject:wearV];
    [_NorequestVArr addObject:photoV];
    [_NorequestVArr addObject:setComV];
    [_NorequestVArr addObject:digtalV];
    [_NorequestVArr addObject:setComOutV];
    
    _secondMenuArr = [NSMutableArray array];
    _thirdMenuArr = [NSMutableArray array];
    _secondValueArr = [NSMutableArray array];
     _valueArr = @[@"57",@"16",@"702",@"790",@"688",@"227",@"590",@"591",@"432"];
    [self requestDataWithIndex:0];
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerClass:[DFProductsRightTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"a"];
    self.tableView.rowHeight = 60;
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DFront.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"create table menu(data blob)"];
    }else
    {
        NSLog(@"打开数据库失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from menu"];
    while ([resultSet next] ) {
        NSData *data = [resultSet dataForColumn:@"data"];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        for (NSString *key in dic[@"abc"]) {
            [_secondMenuArr addObject:key];
            
            [_secondMenuArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                return [obj1 compare:obj2];
            }];
        }
        for (int i = 0; i < _secondMenuArr.count; i++) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in [dic[@"abc"] objectForKey:_secondMenuArr[i]]) {
                DFProductSortListModel *model = [[DFProductSortListModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [arr addObject:model];
            }
            [_secondValueArr addObject:arr];
        }
    }
}

- (void)requestDataWithIndex:(NSInteger)index
{
    NSString *urlString = [@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_Manu_V1&subcateId=" stringByAppendingString:_valueArr[index]];
    _selectedIndex = index;
    [PKRequestManager  requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        
        [_secondMenuArr removeAllObjects];
        [_thirdMenuArr removeAllObjects];
        [_secondValueArr removeAllObjects];
        
        [_dataBase executeUpdate:@"delete from menu"];
        [_dataBase executeUpdate:@"insert into menu (data) values (?)",data];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dict in dic[@"rank"]) {
            DFProductSortListModel *model = [[DFProductSortListModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [array addObject:model];
        }
        [_secondValueArr addObject:array];
        [_secondMenuArr addObject:@" 热"];
        for (NSString *key in dic[@"abc"]) {
            [_secondMenuArr addObject:key];
            [_secondMenuArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                return [obj1 compare:obj2];
            }];
        }
 
        for (int i = 1; i < _secondMenuArr.count; i++) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in [dic[@"abc"] objectForKey:_secondMenuArr[i]]) {
                DFProductSortListModel *model = [[DFProductSortListModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [arr addObject:model];
            }
            [_secondValueArr addObject:arr];
        }
        [self.tableView reloadData];
    }
        error:^(NSError *error) {
        NSLog(@"请求失败%@",error);
        }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_lastIndex < 9) {
        return _secondValueArr.count;
    }else
    {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_lastIndex < 9) {
         return [_secondValueArr[section] count];
    }else
    {
        return [_NorequestArr[_lastIndex - 9] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_lastIndex < 9) {
         DFProductsRightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    DFProductSortListModel *model = _secondValueArr[indexPath.section][indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"-text"]];
    cell.title.text = model.name;
    return cell;
    }else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a" forIndexPath:indexPath];
    
        cell.textLabel.text = _NorequestArr[_lastIndex - 9][indexPath.row] ;
        return cell;
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_lastIndex > 8) {
        return nil;
    }else{
        if (section == 0) {
            return @" 热门品牌";
        }else
        {
            return _secondMenuArr[section];
        }
    }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_lastIndex > 8) {
        return nil;
    }else{
          return _secondMenuArr;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DFProductsDetailViewController *detailController = [[DFProductsDetailViewController alloc]init];

    if (_lastIndex < 9) {
         detailController.differentVa = dfProductsRightTableViewController;
         detailController.manuId = [_secondValueArr[indexPath.section][indexPath.row] ID];
         detailController.brand = [_secondValueArr[indexPath.section][indexPath.row] name];
         detailController.subcateId = _valueArr[_selectedIndex];
    }else
    {
        detailController.differentVa = dfProductsRightTableViewController;
        detailController.brand = _NorequestArr[_lastIndex - 9][indexPath.row];
        detailController.manuId = @"";
        detailController.subcateId = _NorequestVArr[_lastIndex - 9][indexPath.row];
    }
    [self.nav pushViewController:detailController animated:YES];
}

@end
